<?php


namespace app\index\controller;


use app\common\controller\Apicommon;
use app\common\controller\Excel;
use app\index\model\Device;
use app\index\model\DeviceCategory;
use think\Db;

class Door extends Apicommon
{
    use Excel;

    public function initialize()
    {
//        parent::initialize();
        header('Access-Control-Allow-Headers: content-type,authorization,token');
        header('Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS');
        header('Access-Control-Allow-Origin: *');
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            echo 1;die;
        }
        // 安全校验
        if(empty(session('user_auth.uid'))){
            $this->redirect(url('index/index/login'));
        }else{
            $this->uid = session('user_auth.uid');
        }
    }

    public function door_list($gear_id = null)
    {
        $gear_id = input('gear_id');
        $door = \app\index\model\Door::all(['gear_id'=>$gear_id]);
        foreach ($door as $key => &$value) {
            $value['free'] = Db::name('device')->where('door_id',$value['id'])->where('status',3)->count('id');
            $value['charge'] = Db::name('device')->where('door_id',$value['id'])->where('status',2)->count('id');
        }
        $this->assign('door',$door);
        return $this->fetch();
    }
    public function device_of_door($door_id = null)
    {
        $door_id = $door_id ?: input('door_id');
        $device = Device::all(['door_id'=>$door_id]);
        $this->assign('device',$device);
        return $this->fetch();
    }
    public function door_edit($door_id = null)
    {
        $id = $door_id ?: input('door_id');
        if (empty($id))
            $this->error('参数错误');

        if ($this->request->isPost()) {
            if (!input('device_category') || !input('device_name') || !input('device_model') || !input('door_id'))
                $this->error('参数错误');
            \app\index\model\Door::update([
                'device_category'=>input('device_category'),
                'device_name'=>input('device_name'),
                'device_model'=>input('device_model'),
            ],['id'=>$id]);
            $this->success('保存成功');
        }
        $this->assign('door_id',$door_id);

        // 设备类别
        $category_list = DeviceCategory::all();
        $this->assign('category_list',$category_list);

        // 设备名称
        $device_name = Device::where([])->field('device_name')->distinct('device_name')->select();
        $this->assign('device_name',$device_name);

        // 设备型号
        $device_model = Device::where([])->field('device_model')->distinct('device_model')->select();
        $this->assign('device_model',$device_model);

        $row = \app\index\model\Door::get($id);
        $this->assign('row',$row);

        return $this->fetch();
    }
}